package com.newdjk.newdoctor.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.dialog.GroupButtonDialog;
import com.newdjk.newdoctor.entity.AppEntity;
import com.newdjk.newdoctor.entity.UpdateEntity;
import com.newdjk.newdoctor.receiver.NotificationClickReceiver;
import com.newdjk.newdoctor.utils.AppUtils;
import com.newdjk.newdoctor.utils.InstallApkUtil;
import com.newdjk.newdoctor.utils.NetworkUtil;
import com.newdjk.newdoctor.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MyService extends Service {
    private static final String TAG = "MyService";
    private NotificationManager notificationManager2;
    private String notificationId = "channelId";
    private String notificationName = "channelName";
    private Notification mNotification;


    //-----------------------------------------------app下载部分内容-------------------------------------------------
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;
    private Notification notification;
    private int mCurentPercent = 0;
    private int channelID = 1;
    private String mApkUrl = "";
    private static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + "doctor.apk";
    public static boolean isDownload = false;
    String PRIMARY_CHANNEL = "my_channel_01";
    String name = "我是渠道名字";
    private GroupButtonDialog mDialog;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon))
                .setContentTitle("芸医机构版")
                .setContentText("我正在运行");
        //设置Notification的ChannelID,否则不能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationId);
        }
        Notification notification = builder.build();
        return notification;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // startForeground(1, new Notification()); //这个id不要和应用内的其他同志id一样，不行就写 int.maxValue()        //context.startForeground(SERVICE_ID, builder.getNotification());
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager2.createNotificationChannel(channel);
            startForeground(2, getNotification());
        }
        EventBus.getDefault().register(this);
        initNotification();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadApp(AppEntity entity) {
        Log.d("Myservice", "收到下载app消息提示");

        final String apkUrl = entity.getAppPath();
        mApkUrl = apkUrl;
        int apkCode = entity.getAppVersion();
        int versionCode = AppUtils.getAppVersionCode(this);
        ToastUtil.setToast("正在下载中，在顶部状态栏中可以查看进度！");
        startDownload();

    }

    private void startDownload() {

        FileDownloader.getImpl().create(mApkUrl).setWifiRequired(false).setPath(DOWNLOAD_PATH).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                isDownload = true;
                int p = (int) ((double) soFarBytes / (double) totalBytes * 100);
                Log.d(TAG, "正在下载" + soFarBytes + "   总数" + totalBytes);

                mCurentPercent = p;
                builder.setProgress(100, p, false);
                builder.setContentText("下载进度:" + p + "%");
                builder.setContentTitle("正在更新...");
                notification = builder.build();
                notificationManager.notify(channelID, notification);

            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {


            }

            @Override
            protected void completed(BaseDownloadTask task) {
                Log.d(TAG, "下载完成");
                isDownload = false;
                if (builder != null) {

                    mCurentPercent = 100;
                    builder.setProgress(100, 100, false);
                    builder.setContentText("下载完成:" + 100 + "%");
                    builder.setContentTitle("下载完成，点击进行安装");
                    notification = builder.build();
                    notificationManager.notify(channelID, notification);
                }

                InstallApkUtil installApkUtil = new InstallApkUtil();
                installApkUtil.installApk(MyService.this, DOWNLOAD_PATH);

            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                Log.d(TAG, "下载失败");
                isDownload = false;
                if (builder != null) {
                    builder.setContentTitle("下载失败");
                    notification = builder.build();
                    notificationManager.notify(channelID, notification);
                }

                if (mDialog == null) {
                    mDialog = new GroupButtonDialog(MyService.this);
                }
                mDialog.show("下载失败", "下载失败，是否重新下载？", new GroupButtonDialog.DialogListener() {
                    @Override
                    public void cancel() {
                        mDialog = null;
                    }

                    @Override
                    public void confirm() {
                                   /* UpdateManage updateManage = new UpdateManage(getContext(), apkUrl);
                                    updateManage.showDownloadDialog();*/
                        mDialog = null;
                        if (TextUtils.isEmpty(mApkUrl)) {
                            return;
                        }
                        Log.d(TAG, "重新下载");
                        if (NetworkUtil.isNetworkAvailable(getApplicationContext())) {
                            Log.w(TAG, "恢复任务失败，网络未连接");
                            ToastUtil.setToast("网络连接失败，请检查网络");
                            return;
                        }
                        initNotification();
                    }
                });
            }

            @Override
            protected void warn(BaseDownloadTask task) {


            }
        }).start();
    }

    //初始化通知
    private void initNotification() {

//        notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
//        builder = new NotificationCompat.Builder(MyApplication.getInstance());
//        builder.setContentTitle("正在更新...") //设置通知标题
//                .setSmallIcon(R.mipmap.icon)
//                .setLargeIcon(BitmapFactory.decodeResource(MyApplication.getInstance().getResources(), R.mipmap.icon)) //设置通知的大图标
//                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
//                .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
//                .setAutoCancel(true)//设置通知被点击一次是否自动取消
//                .setContentText("下载进度:" + "0%")
//                .setProgress(100, 0, false);
//        notification = builder.build();//构建通知对象

        notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//适配8.0,自行查看8.0的通知，主要是NotificationChannel
            NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL,
                    "Primary Channel", NotificationManager.IMPORTANCE_DEFAULT);
            chan1.setLightColor(Color.GREEN);
            chan1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(chan1);
            builder = new NotificationCompat.Builder(this, PRIMARY_CHANNEL);
        } else {
            builder = new NotificationCompat.Builder(this, null);
        }
        builder.setContentText("下载进度:" + "0%")//notification的一些设置，具体的可以去官网查看
                .setContentTitle("正在更新...") //设置通知标题
                .setTicker("正在下载")
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setOnlyAlertOnce(true)
                .setWhen(System.currentTimeMillis())
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon))
                .setSmallIcon(R.mipmap.icon);
        builder.setProgress(100, 0, false);//显示下载进度
        // TODO: 2020/8/7 安装app还有问题
        Intent intent = new Intent(this, NotificationClickReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        // 如果存在，启动安装流程
        mNotification = builder.build();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userEventBus(UpdateEntity updateEntity) {
        Log.d("Myservice", "收到安装app消息");
        if (isDownload) {
            ToastUtil.setToast("app正在更新中，请下载完成后点击进行安装");
            return;
        }
        InstallApkUtil installApkUtil = new InstallApkUtil();
        installApkUtil.installApk(MyService.this, DOWNLOAD_PATH);

    }
}
